package com.sxhalo.fsms.controller.api;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.*;
import com.sxhalo.fsms.export.ExcelUtils;
import com.sxhalo.fsms.export.ExportSetInfo;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.ILogDownloadService;
import com.sxhalo.fsms.service.ILogExceptionService;
import com.sxhalo.fsms.service.ILogOperationService;
import com.sxhalo.fsms.service.ILogSysRunningService;
import com.sxhalo.fsms.util.ApiResult;
import com.sxhalo.fsms.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/api")
public class LogOperateController extends BaseController {

	@Autowired
	private ILogOperationService logService;
	@Autowired
	private ILogDownloadService  logDownLoadService;
	@Autowired
	private ILogExceptionService  logExceptionService;
	@Autowired
	private ILogSysRunningService  logSysRunningService;


	@ResponseBody
	@RequestMapping(value = "/log", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findDic(Integer typeId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = getWhere(req);
		String order = " create_time desc";
		return findList(current, pageSize, where, order, logService);
	}





	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "操作日志")
	@RequestMapping(value = "/log", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult delLog(Integer id, HttpServletRequest req) {
		logService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "操作日志")
	@RequestMapping(value = "/log/batchdel", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult batchDelLog(String  ids, HttpServletRequest req) {
		logService.deleteByWhere( " log_id in ("+ids+")");
		return ApiResult.retOK(req);
	}


	/*下载日志*/
	@ResponseBody
	@RequestMapping(value = "/downLoadLog", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findDownLoadLogList(Integer typeId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = getWhere(req);
		String order = " download_time desc";
		return findList(current, pageSize, where, order, logDownLoadService);
	}
	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "下载日志")
	@RequestMapping(value = "/downLoadLog", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult delDownLoadLog(Integer id, HttpServletRequest req) {
		logDownLoadService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "下载日志")
	@RequestMapping(value = "/downLoadLog/batchdel", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult batchDelDownLoadLog(String  ids, HttpServletRequest req) {
		logDownLoadService.deleteByWhere( " id in ("+ids+")");
		return ApiResult.retOK(req);
	}
	
	/*异常日志*/
	@ResponseBody
	@RequestMapping(value = "/exceptionLog", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findExceptionLogList(Integer typeId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = getWhere(req);
		String order = " create_time desc";
		return findList(current, pageSize, where, order, logExceptionService);
	}
	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "异常日志")
	@RequestMapping(value = "/exceptionLog", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult delExceptionLog(Integer id, HttpServletRequest req) {
		logExceptionService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "操作日志")
	@RequestMapping(value = "/exceptionLog/batchdel", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult batchExceptionLog(String  ids, HttpServletRequest req) {
		logExceptionService.deleteByWhere( " log_id in ("+ids+")");
		return ApiResult.retOK(req);
	}
	
	/*运行日志*/
	@ResponseBody
	@RequestMapping(value = "/runningLog", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findRunningLogList(Integer typeId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = getWhere(req);
		String order = " create_time desc";
		return findList(current, pageSize, where, order, logSysRunningService);
	}

	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "运行日志")
	@RequestMapping(value = "/runningLog", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult delRunningLog(Integer id, HttpServletRequest req) {
		logSysRunningService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "运行日志")
	@RequestMapping(value = "/runningLog/batchdel", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult batchDelRunningLog(String  ids, HttpServletRequest req) {
		logSysRunningService.deleteByWhere( " log_id in ("+ids+")");
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "导出", modelName = "操作日志")
	@RequestMapping(value = "/log/exportExcel", method = RequestMethod.GET)
	public void deviceDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "操作日志列表";
		String[] Userkeys = { "createTime", "machineIp", "userName", "moduleName", "operationName", "operationData" };

		String where = getWhere(request);
		List<LogOperation> data = logService.findPagerList(0, -1, where, "");
		ExportSetInfo info = new ExportSetInfo();
		info.setHeadNames(createUsersExcelHead());
		info.setDatalist(createUserListRecord(data));
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);
	}
	// 表头选择
	private List<String[]> createUsersExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "创建时间", "ip", "用户名", "模块名称", "功能名称", "参数" };
		headlist.add(row1);
		return headlist;
	}
	private List<Map<String, Object>> createUserListRecord(List<LogOperation> data) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (LogOperation fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("createTime", DateUtil.sdf.format(fd.getCreateTime()));
			mapValue.put("machineIp", fd.getMachineIp());
//			mapValue.put("userId", fd.getUserId());
			mapValue.put("userName", fd.getUserName());
			mapValue.put("moduleName", fd.getModuleName());
			mapValue.put("operationName", fd.getOperationName());
			mapValue.put("operationData", fd.getOperationData());
			listmap.add(mapValue);
		}

		return listmap;
	}


	@ResponseBody
	@SysControllerLog(operationName = "导出", modelName = "异常日志")
	@RequestMapping(value = "/exceptionLog/exportExcel", method = RequestMethod.GET)
	public void exceptionLogDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "异常日志列表";
		String[] Userkeys = { "createTime", "machineIp", "userName", "moduleName", "operationName", "operationData","message" };

		String where = getWhere(request);
		List<LogException> data = logExceptionService.findPagerList(0, -1, where, "");
		ExportSetInfo info = new ExportSetInfo();
		info.setHeadNames(createExceptionLogExcelHead());
		info.setDatalist(createExceptionListRecord(data));
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);
	}
	// 表头选择
	private List<String[]> createExceptionLogExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "创建时间", "ip", "用户名", "模块名称", "功能名称", "参数" ,"异常信息"};
		headlist.add(row1);
		return headlist;
	}
	private List<Map<String, Object>> createExceptionListRecord(List<LogException> data) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (LogException fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("createTime", DateUtil.sdf.format(fd.getCreateTime()));
			mapValue.put("machineIp", fd.getMachineIp());
			mapValue.put("userName", fd.getUserName());
			mapValue.put("moduleName", fd.getModuleName());
			mapValue.put("operationName", fd.getOperationName());
			mapValue.put("operationData", fd.getOperationData());
			mapValue.put("message", fd.getMessage());
			listmap.add(mapValue);
		}

		return listmap;
	}



	@ResponseBody
	@SysControllerLog(operationName = "导出", modelName = "运行日志")
	@RequestMapping(value = "/runningLog/exportExcel", method = RequestMethod.GET)
	public void runningLogDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "运行日志列表";
		String[] Userkeys = { "createTime", "logType", "moduleName", "operationName", "operationData"};
		String where = getWhere(request);
		List<LogSysRunning> data = logSysRunningService.findPagerList(0, -1, where, "");
		ExportSetInfo info = new ExportSetInfo();
		info.setHeadNames(createExceptionLogExcelHead());
		info.setDatalist(createRunningLogListRecord(data));
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);
	}

	// 表头选择
	private List<String[]> createRunningLogExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "创建时间", "类型",  "模块名称", "功能名称", "参数" };
		headlist.add(row1);
		return headlist;
	}

	private List<Map<String, Object>> createRunningLogListRecord(List<LogSysRunning> data) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (LogSysRunning fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("createTime", DateUtil.sdf.format(fd.getCreateTime()));
			mapValue.put("logType", fd.getLogType());
			mapValue.put("moduleName", fd.getModuleName());
			mapValue.put("operationName", fd.getOperationName());
			mapValue.put("operationData", fd.getOperationData());

			listmap.add(mapValue);
		}

		return listmap;
	}


	@ResponseBody
	@SysControllerLog(operationName = "导出", modelName = "下载日志")
	@RequestMapping(value = "/downLoadLog/exportExcel", method = RequestMethod.GET)
	public void downLoadLogDownload(String keyword, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "下载日志列表";
		String[] Userkeys = { "downloadTime", "userName", "logType", "fileName", "fileSize"};
		String where = getWhere(request);
		List<LogDownload> data = logDownLoadService.findPagerList(0, -1, where, "");
		ExportSetInfo info = new ExportSetInfo();
		info.setHeadNames(createDownLoadLogExcelHead());
		info.setDatalist(createDownLoadLogListRecord(data));
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);
	}

	// 表头选择
	private List<String[]> createDownLoadLogExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "下载时间", "用户",  "文件类型", "文件名称", "文件大小" };
		headlist.add(row1);
		return headlist;
	}

	private List<Map<String, Object>> createDownLoadLogListRecord(List<LogDownload> data) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (LogDownload fd : data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("downloadTime", DateUtil.sdf.format(fd.getDownloadTime()));
			mapValue.put("userName", fd.getUserName());
			mapValue.put("logType", fd.getLogType());
			mapValue.put("fileName", fd.getFileName());
			mapValue.put("fileSize", fd.getFileSize());


			listmap.add(mapValue);
		}

		return listmap;
	}

	String getWhere( HttpServletRequest req){
		String where = "";

		if(!isBlank(req.getParameter("createTime"))) {
			where += " and  create_time like '" + req.getParameter("createTime").substring(0,10) .trim() + "%'";
		}
		if(!isBlank(req.getParameter("machineIp"))) {
			where += " and  machine_ip like '%" + req.getParameter("machineIp").trim() + "%'";
		}
		if(!isBlank(req.getParameter("userName"))) {
			where += " and user_name like '%" + req.getParameter("userName").trim() + "%'";
		}
		if(!isBlank(req.getParameter("operationName"))) {
			where += " and  operation_name like '%" + req.getParameter("operationName").trim() + "%'";
		}
		if(!isBlank(req.getParameter("moduleName"))) {
			where += " and  module_name like '%" + req.getParameter("moduleName").trim() + "%'";
		}
		if(!isBlank(req.getParameter("logType"))) {
			where += " and  log_type like '%" + req.getParameter("logType") .trim() + "%'";
		}
		if(!isBlank(req.getParameter("logType"))) {
			where += " and  log_type like '%" + req.getParameter("logType") .trim() + "%'";
		}
		if(!isBlank(req.getParameter("fileName"))) {
			where += " and file_name like '%" + req.getParameter("fileName").trim() + "%'";
		}
		if(!isBlank(req.getParameter("logType"))) {
			where += " and log_type like '" + req.getParameter("logType").trim()+ "'";
		}
		if(!isBlank(req.getParameter("downloadTime"))) {

			where += " and download_time like '" + req.getParameter("downloadTime").substring(0, 10) + "%'";
		}

		if(!where.equals("")){
			where=where.substring(5);
		}
		return where;
	}

}
